package com.aistar.scheduler;

import com.aistar.mapper.SeckillMapper;
import com.aistar.pojo.Seckill;
import com.aistar.pojo.SeckillExample;
import com.aistar.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class SeckillTask {
    @Autowired
    private SeckillMapper seckillMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Scheduled(cron = "0/300 * * * * ?")
    public void startSeckill(){
        SeckillExample seckillExample = new SeckillExample();
       SeckillExample.Criteria criteria =  seckillExample.createCriteria();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND,0);
        Date time = calendar.getTime();

        System.out.println("time:"+time);

        System.out.println("calendar.getTime():"+calendar.getTime());

        criteria.andSeckillStartTimeLessThan(time).andSeckillEndTimeGreaterThan(time).andSeckillStatusEqualTo(0);
        List<Seckill> seckillList = seckillMapper.selectByExample(seckillExample);
        for (Seckill seckill:seckillList){
            System.out.println(seckill.getSeckillId()+"秒杀活动已经开启");
            //删除以前重复得活动任务
            redisTemplate.delete("seckill:count:"+seckill.getSeckillId());
            //有几个库存商品，则初始化几个list对象
            for (int i =0;i<seckill.getSeckillTotal();i++){
                redisTemplate.opsForList().rightPush("secKill:count:"+seckill.getSeckillId(),seckill.getProductId());
            }
            seckill.setSeckillStatus(1);
            seckillMapper.updateByPrimaryKey(seckill);
        }

    }

    @Scheduled(cron = "0/300 * * * * ?")
    public void endSeckill(){
        SeckillExample seckillExample = new SeckillExample();
        SeckillExample.Criteria criteria =  seckillExample.createCriteria();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND,0);
        Date time = calendar.getTime();
        criteria.andSeckillEndTimeLessThan(time).andSeckillStatusEqualTo(1);
        List<Seckill> seckillList = seckillMapper.selectByExample(seckillExample);
        for (Seckill seckill:seckillList){
            System.out.println("秒杀已经结束");
            seckill.setSeckillStatus(2);
            seckillMapper.updateByPrimaryKey(seckill);
            redisTemplate.delete("seckill:count:"+seckill.getSeckillId());
        }

    }
}
